package com.next

import grails.converters.JSON
import grails.gorm.transactions.Transactional
import org.apache.commons.lang.StringUtils
import org.springframework.security.access.annotation.Secured

import java.text.SimpleDateFormat

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_CONDITION_RULEENGINE', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_PRODUCT_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO', 'ROLE_COO', 'ROLE_POST_LOAN_MANAGER', 'ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER', 'ROLE_COMPLIANCE_MANAGER', 'ROLE_INVESTOR'])
@Transactional(readOnly = true)
class OpportunityController
{
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def billsService
    def opportunityService
    def contactservice
    def springSecurityService
    def assetValueService
    def opportunityNotificationService
    def creditReportService
    def contactService
    def opportunityStatisticsService

    def foticAheadService
    def avicAheadSubmitService

    @Secured(['ROLE_INVESTOR'])
    def indexByInvestor(Integer max)
    {
        params.max = 10
        max = 10

        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def offset = params.offset
        def count
        def list = []
        def list1 = []
        def opportunityList = []
        println "count:" + count
        def opportunityStageList = OpportunityStage.findAll("from OpportunityStage where code in ('10','20','23','43','44','81','82','100')")
        respond list, model: [opportunityCount: count, opportunityStageList: opportunityStageList]
    }

    @Secured(['ROLE_INVESTOR'])
    def searchByInvestor()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0;

        def max = params.max
        def offset = params.offset

        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def status = params["status"]
        def type = params["type"]
        def serialNumber = params["serialNumber"]
        def fullName = params["fullName"]
        def contact = params["contact"]
        def mangerName = params["user"]
        def stageName = params['stage']
        def startTime = params["startTime"]
        def endTime = params["endTime"]
        def city = params["city"]

        def mortgageCertificateType = params["mortgageCertificateType"]
        def contactLevel = params["contactLevel"]
        def actualAmountOfCreditMin = params["actualAmountOfCreditMin"]
        def actualAmountOfCreditMax = params["actualAmountOfCreditMax"]

        def prepareCity = params["prepareCity"]
        def currentStageId = params["currentStage"]
        def currentStage
        if (currentStageId)
        {
            currentStage = OpportunityStage.findById(currentStageId)
        }
        def opportunityRoleList = []
        def count
        String sql = "from WorkflowInstanceUser as otr where otr.user.id = ${user?.id} and otr.stage.id = otr.stage.instance.stage.id"
        String roleSql = "select otr.id from Opportunity as otr where 1=1"
        if (serialNumber)
        {
            sql += " and otr.stage.instance.opportunity.serialNumber like '%${serialNumber}%'"
            roleSql += " and otr.serialNumber like '%${serialNumber}%'"
        }
        if (fullName)
        {
            sql += " and otr.stage.instance.opportunity.fullName like '%${fullName}%'"
            roleSql += " and otr.fullName like '%${fullName}%'"
        }
        if (contact)
        {
            sql += " and otr.stage.instance.opportunity.contact.fullName like '%${contact}%'"
            roleSql += " and otr.contact.fullName like '%${contact}%'"
        }
        if (mangerName)
        {
            sql += " and otr.stage.instance.opportunity.user.fullName like '%${mangerName}%'"
            roleSql += " and otr.user.fullName like '%${mangerName}%'"
        }
        if (stageName)
        {
            sql += " and otr.stage.instance.opportunity.stage.name = '${stageName}'"
            roleSql += " and otr.stage.name = '${stageName}'"
        }

        if (currentStage)
        {
            sql += " and o.stage.id = ${currentStage?.id}"
            roleSql += " and otr.stage.id = ${currentStage?.id}"
        }

        if (startTime && endTime)
        {
            sql += " and otr.stage.instance.opportunity.createdDate between '${startTime}' and '${endTime}'"
            roleSql += " and otr.createdDate between '${startTime}' and '${endTime}'"
        }

        if (city && city != "null")
        {
            sql += " and otr.stage.instance.opportunity.contact.city.name = '${city}'"
            roleSql += " and otr.contact.city.name = '${city}'"
        }
        if (mortgageCertificateType && mortgageCertificateType != "null")
        {
            sql += " and otr.stage.instance.opportunity.mortgageCertificateType.name = '${mortgageCertificateType}'"
            roleSql += " and otr.mortgageCertificateType.name = '${mortgageCertificateType}'"
        }

        if (contactLevel && contactLevel != "null")
        {
            sql += " and otr.stage.instance.opportunity.lender.level.name = '${contactLevel}'"
            roleSql += " and otr.lender.level.name = '${contactLevel}'"
        }

        if (actualAmountOfCreditMin)
        {
            sql += " and otr.stage.instance.opportunity.actualAmountOfCredit >= '${actualAmountOfCreditMin}'"
            roleSql += " and otr.actualAmountOfCredit >= '${actualAmountOfCreditMin}'"
        }

        if (actualAmountOfCreditMax)
        {
            sql += " and otr.stage.instance.opportunity.actualAmountOfCredit <= '${actualAmountOfCreditMax}'"
            roleSql += " and otr.actualAmountOfCredit <= '${actualAmountOfCreditMax}'"
        }


        sql += " order by otr.stage.instance.opportunity.modifiedDate desc"
        //  roleSql += " order by otr.modifiedDate desc"

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd")
        def opportunityList = []
        def list1 = []
        def list = []
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_INVESTOR")))
        {
            roleSql += " and otr.status in ('Completed', 'Pending')"
            roleSql += " and otr.stage.code in ('10','20','23','43','44','81','82','100')"
            roleSql += " and otr.isTest = false"
            roleSql += " order by otr.modifiedDate desc"
            opportunityList = Opportunity.executeQuery(roleSql, [max: max, offset: offset])
            opportunityList?.each {
                def listItem = []
                def opportunityDomain = Opportunity.find("from Opportunity as o where o.id = ${it}")
                listItem.add(opportunityDomain?.id)
                listItem.add(opportunityDomain?.serialNumber)
                listItem.add(opportunityDomain?.type?.name)
                listItem.add(opportunityDomain?.stage?.name)
                listItem.add(opportunityDomain?.status)
                listItem.add(opportunityDomain?.fullName)
                listItem.add(opportunityDomain?.lender?.level?.description)
                listItem.add(opportunityDomain?.contact?.fullName)
                listItem.add(opportunityDomain?.user?.fullName)
                listItem.add(opportunityDomain?.account?.name)
                listItem.add(opportunityDomain?.product?.name)
                listItem.add(opportunityDomain?.loanAmount)
                listItem.add(opportunityDomain?.requestedAmount)
                listItem.add(opportunityDomain?.actualAmountOfCredit)
                listItem.add(opportunityDomain?.loanDuration)
                listItem.add(opportunityDomain?.actualLoanDuration)
                listItem.add(opportunityDomain?.mortgageCertificateType?.name)
                listItem.add(opportunityDomain?.causeOfFailure?.name)
                listItem.add(opportunityDomain?.lastAction?.name)
                listItem.add(opportunityDomain?.createdDate)
                listItem.add(opportunityDomain?.memo)


                list.add(listItem)
            }
            list1 = Opportunity.executeQuery(roleSql)
            count = list1.size()
        }
        def opportunityStageList = OpportunityStage.findAll("from OpportunityStage where code in ('10','20','23','43','44','81','82','100')")
        respond list, model: [list: list, opportunityCount: count, params: params, opportunityStageList: opportunityStageList], view: 'indexByInvestor'
    }

    @Secured(['ROLE_INVESTOR'])
    @Transactional
    def showByInvestor(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def history
        if (opportunity && opportunity?.serialNumber)
        {
            history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
        }
        def code = opportunity?.stage?.code
        def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
        def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


        def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
        def opportunityStage = OpportunityStage.findByCode("38")

        //        def creditReport = CreditReport.findAllByOpportunity(opportunity)
        def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
        //        def liquidityRiskReport = LiquidityRiskReport.findAll("from LiquidityRiskReport where opportunity.id = ${opportunity?.id} order by createdDate ASC")
        def activities = Activity.findAllByOpportunity(opportunity)

        def currentProgress = 0
        def totalProgress = 0
        def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
        def progressPercent
        def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")
        def transactionRecords
        if (!opportunity?.type || opportunity?.type?.code == "10")
        {
            transactionRecords = TransactionRecord.findAll("from TransactionRecord where opportunity.id = ${opportunity?.id} order by createdDate asc")
        } else
        {
            transactionRecords = TransactionRecord.findAll("from TransactionRecord where opportunity.id = ${opportunity?.parent?.id} order by createdDate asc")
        }


        def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)

        def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        def subUsers = []
        def reportings
        if (currentRole?.authority?.name == 'Approval')
        {
            reportings = Reporting.findAllByManager(user)
            reportings?.each {
                subUsers.add(it?.user)
            }
        }

        if (totalProgress > 0)
        {
            progressPercent = currentProgress / totalProgress
        } else
        {
            progressPercent = 0
        }


        def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")
        def canSpecialApproval = false
        def specialApprovalAttachments = Attachments.findByOpportunityAndType(opportunity, AttachmentType.findByName('特批签呈'))
        if (specialApprovalAttachments && opportunity?.status == 'Failed' && currentRole?.authority?.name == 'Approval')
        {
            if (!(opportunity?.subtype))
            {
                canSpecialApproval = true
            } else if (opportunity?.subtype?.name == '正常审批')
            {
                canSpecialApproval = true
            }
        }
        def canQueryPrice = true

        def regionalRiskManageStage = OpportunityStage.findByCode("08")

        def canCreditReportShow = false
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            canCreditReportShow = true
        } else if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_BRANCH_OFFICE_RISK_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_HEAD_OFFICE_RISK_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_GENERAL_RISK_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_CUSTOMER_SERVICE_REPRESENTATIVE")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_COMPLIANCE_MANAGER")))
        {
            if (currentRole?.authority?.name == 'Approval')
            {
                canCreditReportShow = true
            }
        }
        def canAttachmentsShow = false
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_COMPLIANCE_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_GENERAL_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_COO")))
        {
            canAttachmentsShow = true
        } else if (currentRole?.authority?.name == 'Approval')
        {
            canAttachmentsShow = true
        }
        def canPhotosShow = false
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_CUSTOMER_SERVICE_REPRESENTATIVE")))
        {
            canPhotosShow = true
        }
        def canLoanReceiptShow = false
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ACCOUNT_MANAGER")))
        {
            canLoanReceiptShow = true
        }

        def canInterestEdit = true
        def loanCompletionStage = OpportunityStage.findByCode("10")
        if ((opportunity?.parent && opportunity?.type?.code == '30') || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER")))
        {
            canInterestEdit = true
        }


        def canbillsShow = false

        def billsItems
        def bills = Bills.findByOpportunity(opportunity)
        if (opportunity?.type?.name == "抵押贷款" && bills)
        {
            billsItems = BillsItem.findAllByBills(bills)
        } else if (opportunity?.type?.name != "抵押贷款")
        {
            bills = Bills.findByOpportunity(opportunity?.parent)
            if (bills)
            {
                billsItems = BillsItem.findAllByBills(bills)
            }
        }
        def opportunityComments = OpportunityComments.findAllByOpportunityAndAction(opportunity, null)
        def opportunityWorkflows = []
        def territory = opportunity?.territory
        if (!territory)
        {
            territory = TerritoryAccount.findByAccount(opportunity?.account)?.territory
        }
        def territoryOpportunityWorkflows = TerritoryWorkflow.findAllByTerritory(territory)
        territoryOpportunityWorkflows?.each {
            opportunityWorkflows.add(it?.workflow)
        }
        //layout
        def opportunityLayout
        if (!opportunityLayout)
        {
            opportunityTeams?.each {
                if (it?.user == user && it?.opportunityLayout)
                {
                    opportunityLayout = it?.opportunityLayout?.name
                }
            }
        }
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_INVESTOR")))
        {
            respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                         //                creditReport: creditReport,
                                         opportunityContacts: opportunityContacts,
                                         activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, transactionRecords: transactionRecords, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails,
                                         canSpecialApproval : canSpecialApproval, user: user, houses: houses, opportunityWorkflows: opportunityWorkflows, billsItems: billsItems, canQueryPrice: canQueryPrice, opportunityComments: opportunityComments, canCreditReportShow: canCreditReportShow, canAttachmentsShow: canAttachmentsShow, canPhotosShow: canPhotosShow, canLoanReceiptShow: canLoanReceiptShow, canInterestEdit: canInterestEdit, canbillsShow: canbillsShow],
                view: 'opportunityLayout30'
        }
    }

    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def opportunityLayout24(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunity?.status == "Pending")
        {
            if (opportunityRole && opportunityRole?.authority?.name != "Read")
            {
                def history
                if (opportunity && opportunity?.serialNumber)
                {
                    history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = ? order by modifiedDate desc", [opportunity.serialNumber])
                }
                def code = opportunity?.stage?.code
                def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
                def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


                def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
                def opportunityStage = OpportunityStage.findByCode("38")

                //                def creditReport = CreditReport.findAllByOpportunity(opportunity)
                def opportunityContacts = OpportunityContact.findAll("from OpportunityContact where opportunity.id = ${opportunity.id} order by type.id")
                //        def liquidityRiskReport = LiquidityRiskReport.findAll("from LiquidityRiskReport where opportunity.id = ${opportunity?.id} order by createdDate ASC")
                def activities = Activity.findAllByOpportunity(opportunity)

                def currentProgress = 0
                def totalProgress = 0
                def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
                def progressPercent
                def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

                def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
                def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")

                def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
                def subUsers = []
                def reportings
                if (currentRole?.authority?.name == 'Approval')
                {
                    reportings = Reporting.findAllByManager(user)
                    reportings?.each {
                        subUsers.add(it?.user)
                    }
                }

                respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                             //                    creditReport: creditReport,
                                             opportunityContacts: opportunityContacts,
                                             activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, houses: houses]
            } else
            {
                flash.message = message(code: 'opportunity.edit.permission.denied')
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
                return
            }
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }

    }

    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def opportunityLayout35(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunity?.status == "Pending")
        {
            if (opportunityRole && opportunityRole?.authority?.name != "Read")
            {
                def history
                if (opportunity && opportunity?.serialNumber)
                {
                    history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
                }
                def code = opportunity?.stage?.code
                def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
                def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


                def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
                def opportunityStage = OpportunityStage.findByCode("38")

                //                def creditReport = CreditReport.findAllByOpportunity(opportunity)
                def opportunityContacts = OpportunityContact.findAll("from OpportunityContact where opportunity.id = ${opportunity.id} order by type.id")
                //        def liquidityRiskReport = LiquidityRiskReport.findAll("from LiquidityRiskReport where opportunity.id = ${opportunity?.id} order by createdDate ASC")
                def activities = Activity.findAllByOpportunity(opportunity)

                def currentProgress = 0
                def totalProgress = 0
                def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
                def progressPercent
                def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

                def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
                def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")

                def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
                def subUsers = []
                def reportings
                if (currentRole?.authority?.name == 'Approval')
                {
                    reportings = Reporting.findAllByManager(user)
                    reportings?.each {
                        subUsers.add(it?.user)
                    }
                }

                respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                             //                    creditReport: creditReport,
                                             opportunityContacts: opportunityContacts,
                                             activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, houses: houses]
            } else
            {
                flash.message = message(code: 'opportunity.edit.permission.denied')
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
                return
            }
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }

    }

    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def opportunityLayout39(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunity?.status == "Pending")
        {
            if (opportunityRole && opportunityRole?.authority?.name != "Read")
            {
                def history
                if (opportunity && opportunity?.serialNumber)
                {
                    history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
                }
                def code = opportunity?.stage?.code
                def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
                def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


                def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
                def opportunityStage = OpportunityStage.findByCode("38")

                //                def creditReport = CreditReport.findAllByOpportunity(opportunity)
                def opportunityContacts = OpportunityContact.findAll("from OpportunityContact where opportunity.id = ${opportunity.id} order by type.id")
                //        def liquidityRiskReport = LiquidityRiskReport.findAll("from LiquidityRiskReport where opportunity.id = ${opportunity?.id} order by createdDate ASC")
                def activities = Activity.findAllByOpportunity(opportunity)

                def currentProgress = 0
                def totalProgress = 0
                def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
                def progressPercent
                def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

                def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
                def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")

                def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
                def subUsers = []
                def reportings
                if (currentRole?.authority?.name == 'Approval')
                {
                    reportings = Reporting.findAllByManager(user)
                    reportings?.each {
                        subUsers.add(it?.user)
                    }
                }

                respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                             //                    creditReport: creditReport,
                                             opportunityContacts: opportunityContacts,
                                             activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, houses: houses]
            } else
            {
                flash.message = message(code: 'opportunity.edit.permission.denied')
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
                return
            }
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }

    }

    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def opportunityLayout36(Opportunity opportunity)
    {
        def transactionRecords
        if (!opportunity?.type || opportunity?.type?.code == "10")
        {
            transactionRecords = TransactionRecord.findAll("from TransactionRecord where opportunity.id = ${opportunity?.id} order by plannedStartTime asc")
        } else if (opportunity?.type?.code == "01")
        {
            transactionRecords = TransactionRecord.findAll("from TransactionRecord where opportunity.id = ${opportunity?.id} order by plannedStartTime asc")
        } else
        {
            transactionRecords = TransactionRecord.findAll("from TransactionRecord where opportunity.id = ${opportunity?.parent?.id} order by plannedStartTime asc")
        }

        def billsItems
        def bills = Bills.findByOpportunity(opportunity)
        if (opportunity?.type?.name == "抵押贷款" && bills)
        {
            billsItems = BillsItem.findAllByBills(bills, [sort: "period"])
        } else if (opportunity?.type?.name == "信用贷款" && bills)
        {
            billsItems = BillsItem.findAllByBills(bills, [sort: "period"])
        } else if (opportunity?.type?.name != "抵押贷款")
        {
            bills = Bills.findByOpportunity(opportunity?.parent)
            if (bills)
            {
                billsItems = BillsItem.findAllByBills(bills, [sort: "period"])
            }
        }
        def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)

        def opportunityContacts = OpportunityContact.findAll("from OpportunityContact where opportunity.id = ${opportunity.id} order by type.id")


        def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")



        respond opportunity, model: [bankAccounts: bankAccounts, billsItems: billsItems, opportunityContacts: opportunityContacts, transactionRecords: transactionRecords, opportunityProduct: opportunityProduct]

    }

    /**
     * @Author 班旭娟
     * @CreatedDate 2017-4-25
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def loanApplicationForm(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        def history
        if (opportunity && opportunity?.serialNumber)
        {
            history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
        }
        def code = opportunity?.stage?.code
        def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
        def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


        def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
        def opportunityStage = OpportunityStage.findByCode("38")

        //                def creditReport = CreditReport.findAllByOpportunity(opportunity)
        def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
        //        def liquidityRiskReport = LiquidityRiskReport.findAll("from LiquidityRiskReport where opportunity.id = ${opportunity?.id} order by createdDate ASC")
        def activities = Activity.findAllByOpportunity(opportunity)

        def currentProgress = 0
        def totalProgress = 0
        def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
        def progressPercent
        def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

        def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
        def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")

        def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        def subUsers = []
        def reportings
        if (currentRole?.authority?.name == 'Approval')
        {
            reportings = Reporting.findAllByManager(user)
            reportings?.each {
                subUsers.add(it?.user)
            }
        }
        def attachments = Attachments.findAllByOpportunity(opportunity)
        respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                     //                    creditReport: creditReport,
                                     opportunityContacts: opportunityContacts,
                                     activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, houses: houses, attachments: attachments]

    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def opportunityLayout09Edit(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunity?.status == "Pending")
        {
            if (opportunityRole && opportunityRole?.authority?.name != "Read")
            {
                def history
                if (opportunity && opportunity?.serialNumber)
                {
                    history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
                }
                def code = opportunity?.stage?.code
                def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
                def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


                def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
                def opportunityStage = OpportunityStage.findByCode("38")

                //                def creditReport = CreditReport.findAllByOpportunity(opportunity)
                def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
                //        def liquidityRiskReport = LiquidityRiskReport.findAll("from LiquidityRiskReport where opportunity.id = ${opportunity?.id} order by createdDate ASC")
                def activities = Activity.findAllByOpportunity(opportunity)

                def currentProgress = 0
                def totalProgress = 0
                def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
                def progressPercent
                def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

                def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
                def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")

                def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
                def subUsers = []
                def reportings
                if (currentRole?.authority?.name == 'Approval')
                {
                    reportings = Reporting.findAllByManager(user)
                    reportings?.each {
                        subUsers.add(it?.user)
                    }
                }
                def attachments = Attachments.findAllByOpportunity(opportunity)
                respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                             //                    creditReport: creditReport,
                                             opportunityContacts: opportunityContacts,
                                             activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, houses: houses, attachments: attachments]
            } else
            {
                flash.message = message(code: 'opportunity.edit.permission.denied')
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
                return
            }
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }

    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def opportunityLayout17Edit(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunity?.status == "Pending")
        {
            if (opportunityRole && opportunityRole?.authority?.name != "Read")
            {
                def history
                if (opportunity && opportunity?.serialNumber)
                {
                    history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
                }
                def code = opportunity?.stage?.code
                def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
                def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


                def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
                def opportunityStage = OpportunityStage.findByCode("38")

                //                def creditReport = CreditReport.findAllByOpportunity(opportunity)
                def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
                //        def liquidityRiskReport = LiquidityRiskReport.findAll("from LiquidityRiskReport where opportunity.id = ${opportunity?.id} order by createdDate ASC")
                def activities = Activity.findAllByOpportunity(opportunity)

                def currentProgress = 0
                def totalProgress = 0
                def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
                def progressPercent
                def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

                def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
                def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")

                def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
                def subUsers = []
                def reportings
                if (currentRole?.authority?.name == 'Approval')
                {
                    reportings = Reporting.findAllByManager(user)
                    reportings?.each {
                        subUsers.add(it?.user)
                    }
                }
                respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                             //                    creditReport: creditReport,
                                             opportunityContacts: opportunityContacts,
                                             activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, houses: houses]
            } else
            {
                flash.message = message(code: 'opportunity.edit.permission.denied')
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
                return
            }
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }

    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def opportunityLayout11(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def history
        if (opportunity && opportunity?.serialNumber)
        {
            history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
        }
        def code = opportunity?.stage?.code
        def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
        def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


        def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
        def opportunityStage = OpportunityStage.findByCode("38")

        def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
        def activities = Activity.findAllByOpportunity(opportunity)

        def currentProgress = 0
        def totalProgress = 0
        def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
        def progressPercent
        def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

        def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
        def houses = House.findAllByOpportunity(opportunity)

        def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        def subUsers = []
        def reportings
        if (currentRole?.authority?.name == 'Approval')
        {
            reportings = Reporting.findAllByManager(user)
            reportings?.each {
                subUsers.add(it?.user)
            }
        }
        respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                     //            creditReport: creditReport,
                                     opportunityContacts: opportunityContacts,
                                     activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, houses: houses]
    }

    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def opportunityZhuShen(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def history
        if (opportunity && opportunity?.serialNumber)
        {
            history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
        }
        def code = opportunity?.stage?.code
        def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
        def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


        def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
        def opportunityStage = OpportunityStage.findByCode("38")

        def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
        def activities = Activity.findAllByOpportunity(opportunity)

        def currentProgress = 0
        def totalProgress = 0
        def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
        def progressPercent
        def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

        def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
        def houses = House.findAllByOpportunity(opportunity)

        def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        def subUsers = []
        def reportings
        if (currentRole?.authority?.name == 'Approval')
        {
            reportings = Reporting.findAllByManager(user)
            reportings?.each {
                subUsers.add(it?.user)
            }
        }
        respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                     //            creditReport: creditReport,
                                     opportunityContacts: opportunityContacts,
                                     activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, houses: houses]
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    def applicationForm(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def history
        if (opportunity && opportunity?.serialNumber)
        {
            history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
        }
        def code = opportunity?.stage?.code
        def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
        def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


        def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
        def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
        def activities = Activity.findAllByOpportunity(opportunity)

        def currentProgress = 0
        def totalProgress = 0
        def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
        def progressPercent
        def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")
        def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        def subUsers = []
        def reportings
        def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")

        if (currentRole?.authority?.name == 'Approval')
        {
            reportings = Reporting.findAllByManager(user)
            reportings?.each {
                subUsers.add(it?.user)
            }
        }
        if (totalProgress > 0)
        {
            progressPercent = currentProgress / totalProgress
        } else
        {
            progressPercent = 0
        }
        if (opportunity?.type?.code == '20')
        {
            respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                         //                creditReport: creditReport,
                                         opportunityContacts: opportunityContacts,
                                         activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, houses: houses], view: 'opportunityLayout08'
        } else
        {
            respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                         //                creditReport: creditReport,
                                         opportunityContacts: opportunityContacts,
                                         activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, houses: houses], view: 'opportunityLayout03'
        }
    }

    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_PRODUCT_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO', 'ROLE_COO'])
    def index(Integer max)
    {
        params.max = 10
        max = 10

        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def offset = params.offset

        def list = []
        def count
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ACCOUNT_MANAGER")))
        {
            list = Opportunity.findAll("from Opportunity as o where o.user.id = ${user.id} order by modifiedDate " + "desc", [max: max, offset: offset])
            count = list.size()
        }
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_COMPANY_ADMINISTRATOR")))
        {
            list = Opportunity.findAll("from Opportunity as o where o.user.id = ${user.id} order by modifiedDate " + "desc", [max: max, offset: offset])
            count = list.size()
        }
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            list = Opportunity.findAll("from Opportunity as c order by c.modifiedDate desc", [max: max, offset: offset])
            count = list.size()
        }

        respond list, model: [opportunityCount: count]
    }

    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_PRODUCT_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO', 'ROLE_COO'])
    def searchOpportunity()
    {
        params.max = 10
        def max = 10

        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def offset = params.offset

        def stage = params["stage"]
        if (!OpportunityStage.findByName(stage))
        {
            stage = ""
        }
        def causeOfFailure = params["causeOfFailure"]
        if (!CauseOfFailure.findByName(causeOfFailure))
        {
            causeOfFailure = ""
        }

        String sql = "from Opportunity as o where 1 = 1"
        def serialNumber = params["serialNumber"]
        if (serialNumber)
        {
            sql += " and o.serialNumber = '" + serialNumber + "'"
        }

        def fullName = params["fullName"]
        if (fullName)
        {
            sql += " and o.fullName = '" + fullName + "'"
        }
        if (stage)
        {
            sql += " and o.stage.name = '" + stage + "'"
        }
        if (causeOfFailure)
        {
            sql += " and o.causeOfFailure.name = '" + causeOfFailure + "'"
        }

        def mortgageCertificateType = params["mortgageCertificateType"]
        if (mortgageCertificateType)
        {
            sql += " and o.mortgageCertificateType.name = '" + mortgageCertificateType + "'"
        }


        def list = []
        def count
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ACCOUNT_MANAGER")))
        {
            sql += " and o.user.id = ${user.id} order by modifiedDate desc"
            list = Opportunity.findAll(sql, [max: max, offset: offset])
            count = list.size()
        }
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_COMPANY_ADMINISTRATOR")))
        {
            sql += " and o.user.id = ${user.id} order by modifiedDate desc"
            list = Opportunity.findAll(sql, [max: max, offset: offset])
            count = list.size()
        }
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            sql += " order by modifiedDate desc"
            list = Opportunity.findAll(sql, [max: max, offset: offset])
            count = list.size()
        }

        def opportunity = new Opportunity(params)
        def opportunityStage = OpportunityStage.findByName(stage)
        def causeOfFail = CauseOfFailure.findByName(causeOfFailure)
        opportunity.stage = opportunityStage
        opportunity.causeOfFailure = causeOfFail

        respond list, model: [opportunityCount: count, opportunity: opportunity], view: 'index'
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_COMPLIANCE_MANAGER', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_PRODUCT_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO', 'ROLE_COO', 'ROLE_POST_LOAN_MANAGER', 'ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER'])
    @Transactional
    def show(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def history
        if (opportunity && opportunity?.serialNumber)
        {
            history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = ? order by modifiedDate desc", [opportunity.serialNumber])
        }
        def code = opportunity?.stage?.code

        if (opportunity?.type?.code == "01" && !opportunity?.product)
        {
            opportunity.product = Product.findByName("新e贷")
            opportunity.productAccount = ProductAccount.findByAccountAndProduct(opportunity?.account, Product.findByName("新e贷"))
            opportunity.actualAmountOfCredit = opportunity.loanAmount
            opportunity.actualLoanAmount = opportunity.loanAmount
            if (opportunity.validate())
            {
                opportunity.save(flush: true)
            } else
            {
                println opportunity.errors
            }

            if (!opportunity?.interest)
            {
                def newInterest = new OpportunityProduct()
                def newProductInterest = ProductInterest.findByProductAndproductInterestTypeAndContactLevel(opportunity?.productAccount, ProductInterestType.findByName("基本费率"), ContactLevel.findByName("A"))
                newInterest.productInterestType = newProductInterest?.productInterestType
                newInterest.rate = newProductInterest?.maximumRate == null ? 0 : newProductInterest?.maximumRate * 100
                newInterest.firstPayMonthes = newProductInterest?.firstPayMonthes
                newInterest.installments = newProductInterest?.installments
                newInterest.contractType = ContractType.findByName("借款合同")
                newInterest.opportunity = opportunity
                newInterest.product = opportunity?.productAccount
                if (newInterest.validate())
                {
                    newInterest.save()
                } else
                {
                    println newInterest.errors
                }
            }
        }

        def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
        def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


        def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
        def opportunityStage = OpportunityStage.findByCode("38")

        //删除重复借款人（只删除opportunityContact）
        def lenders = OpportunityContact.findAllByOpportunityAndType(opportunity, OpportunityContactType.findByName("借款人"))
        def lenderContact = OpportunityContact.findByOpportunityAndTypeAndContact(opportunity, OpportunityContactType.findByName("借款人"), opportunity?.lender)
        if (lenders.size() > 1 && lenderContact)
        {
            lenders?.each {
                if (it.contact != opportunity.lender && it.contact.idNumber == opportunity.lender.idNumber)
                {
                    it.delete flush: true
                }
            }
        }

        def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
        def activities = Activity.findAllByOpportunity(opportunity)

        def currentProgress = 0
        def totalProgress = 0
        def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
        def progressPercent
        def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")
        //权利人入库单
        def notarizationsList = []
        if (opportunity?.notarizations)
        {
            notarizationsList = opportunity.notarizations.split(",")
        }
        def transactionRecords = TransactionRecord.findAll("from TransactionRecord where opportunity.id = ${opportunity?.id} order by plannedStartTime asc")
        if (transactionRecords.size() == 0)
        {
            transactionRecords = TransactionRecord.findAll("from TransactionRecord where opportunity.id = ${opportunity?.parent?.id} order by plannedStartTime asc")
        }

        //查询相同房产证的订单（在途非测试）
        def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)

        def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        def subUsers = []
        def reportings
        if (currentRole?.authority?.name == 'Approval')
        {
            reportings = Reporting.findAllByManager(user)
            reportings?.each {
                subUsers.add(it?.user)
            }
        }

        if (totalProgress > 0)
        {
            progressPercent = currentProgress / totalProgress
        } else
        {
            progressPercent = 0
        }

        def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")
        def canSpecialApproval = false
        def specialApprovalAttachments = Attachments.findByOpportunityAndType(opportunity, AttachmentType.findByName('特批签呈'))
        if (specialApprovalAttachments && opportunity?.status == 'Failed' && currentRole?.authority?.name == 'Approval')
        {
            if (!(opportunity?.subtype))
            {
                canSpecialApproval = true
            } else if (opportunity?.subtype?.name == '正常审批')
            {
                canSpecialApproval = true
            }
        }
        def canQueryPrice = true
        def regionalRiskManageStage
        if (opportunity?.type?.code == "02")
        {
            regionalRiskManageStage = OpportunityStage.findByName("审批已完成（企业）")
        } else if (opportunity?.type?.code == "03")
        {
            regionalRiskManageStage = OpportunityStage.findByName("审批已完成（车贷）")
        } else
        {
            regionalRiskManageStage = OpportunityStage.findByCode("08")
        }

        def canCreditReportShow = false
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_COMPLIANCE_MANAGER")))
        {
            canCreditReportShow = true
        } else if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_BRANCH_OFFICE_RISK_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_HEAD_OFFICE_RISK_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_GENERAL_RISK_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_CUSTOMER_SERVICE_REPRESENTATIVE")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_COMPLIANCE_MANAGER")))
        {
            if (currentRole?.authority?.name == 'Approval')
            {
                canCreditReportShow = true
            }
        }

        def canAttachmentsShow = false
        def role1 = WorkflowInstanceUser.executeQuery("select id from WorkflowInstanceUser where authority.name = 'Approval' and user.id = ${user.id} and stage.name = '抵押已完成' and stage.instance.opportunity.id = ${opportunity.id}")
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_COMPLIANCE_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_GENERAL_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_COO")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_BRANCH_GENERAL_MANAGER")))
        {
            canAttachmentsShow = true
        } else if (currentRole?.authority?.name == 'Approval')
        {
            canAttachmentsShow = true
        }
        if (role1 && opportunity.stage?.code == "44")
        {
            canAttachmentsShow = true
        }
        def canPhotosShow = false
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_CUSTOMER_SERVICE_REPRESENTATIVE")))
        {
            canPhotosShow = true
        }
        def canLoanReceiptShow = false
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ACCOUNT_MANAGER")))
        {
            canLoanReceiptShow = true
        }

        def canInterestEdit = true
        def loanCompletionStage = OpportunityStage.findByCode("08")
        if ((opportunity?.parent && opportunity?.type?.code == '30') || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER")))
        {
            canInterestEdit = true
        }


        def canbillsShow = false

        def users = OpportunityContact.findAllByOpportunity(opportunity?.parent)
        def borrowers = ""
        users.each {
            borrowers += it.contact?.fullName + ","
        }
        if (users)
        {
            borrowers = StringUtils.substringBeforeLast(borrowers, ",")
        }
        def billsItems
        def bills = Bills.findByOpportunity(opportunity)
        billsItems = BillsItem.findAllByBills(bills, [sort: "period"])
        if (billsItems.size() == 0)
        {
            bills = Bills.findByOpportunity(opportunity?.parent)
            if (bills)
            {
                billsItems = BillsItem.findAllByBills(bills, [sort: "period"])
            }
        }

        def opportunityComments = OpportunityComments.findAllByOpportunityAndAction(opportunity, null)
        def opportunityWorkflows = []
        def territory = opportunity?.territory
        if (!territory)
        {
            territory = TerritoryAccount.findByAccount(opportunity?.account)?.territory
        }
        def territoryOpportunityWorkflows = TerritoryWorkflow.findAllByTerritory(territory)
        territoryOpportunityWorkflows?.each {
            opportunityWorkflows.add(it?.workflow)
        }
        //layout
        def instanceStageId = params['instanceStage']
        def instanceStage = WorkflowInstanceStage.findById(instanceStageId)
        def currentWorkflowInstance
        if (instanceStage)
        {
            currentWorkflowInstance = instanceStage?.instance
        } else if (opportunityFlows?.size() == 1)
        {
            currentWorkflowInstance = opportunityFlows[0]
        }


        def opportunityLayout
        if (!opportunityLayout)
        {
            if (instanceStage)
            {
                opportunityLayout = instanceStage?.opportunityLayout?.name
            } else
            {
                opportunityFlows?.each {
                    if (it?.status == WorkflowInstanceStatus.findByName('Pending'))
                    {
                        opportunityLayout = it?.stage?.opportunityLayout?.name
                    }
                }
            }

            opportunityTeams?.each {
                if (it?.user == user && it?.opportunityLayout)
                {
                    opportunityLayout = it?.opportunityLayout?.name
                }
            }
        }
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                         //                creditReport: creditReport,
                                         opportunityContacts: opportunityContacts, borrowers: borrowers, notarizationsList: notarizationsList,
                                         activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, transactionRecords: transactionRecords, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails,
                                         canSpecialApproval : canSpecialApproval, user: user, houses: houses, opportunityWorkflows: opportunityWorkflows, billsItems: billsItems, canQueryPrice: canQueryPrice, opportunityComments: opportunityComments, canCreditReportShow: canCreditReportShow, canAttachmentsShow: canAttachmentsShow, canPhotosShow: canPhotosShow, canLoanReceiptShow: canLoanReceiptShow, canInterestEdit: canInterestEdit, canbillsShow: canbillsShow, currentWorkflowInstance: currentWorkflowInstance], view: 'administrator'
        } else if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER")))
        {
            respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                         //                creditReport: creditReport,
                                         opportunityContacts: opportunityContacts, transactionRecords: transactionRecords, borrowers: borrowers, notarizationsList: notarizationsList,
                                         activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, canSpecialApproval: canSpecialApproval, user: user, houses: houses, opportunityWorkflows: opportunityWorkflows, billsItems: billsItems,
                                         canQueryPrice      : canQueryPrice, opportunityComments: opportunityComments, canCreditReportShow: canCreditReportShow, canAttachmentsShow: canAttachmentsShow, canPhotosShow: canPhotosShow, canLoanReceiptShow: canLoanReceiptShow, canInterestEdit: canInterestEdit, canbillsShow: canbillsShow, currentWorkflowInstance: currentWorkflowInstance], view: 'postLoanManager01'
        } else if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_COMPLIANCE_MANAGER")))
        {
            respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                         opportunityContacts: opportunityContacts, transactionRecords: transactionRecords, borrowers: borrowers, notarizationsList: notarizationsList,
                                         activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails,
                                         canSpecialApproval : canSpecialApproval, user: user, houses: houses, opportunityWorkflows: opportunityWorkflows, billsItems: billsItems,
                                         canQueryPrice      : canQueryPrice, opportunityComments: opportunityComments, canCreditReportShow: canCreditReportShow, canAttachmentsShow: canAttachmentsShow, canPhotosShow: canPhotosShow, canLoanReceiptShow: canLoanReceiptShow, canInterestEdit: canInterestEdit, canbillsShow: canbillsShow, currentWorkflowInstance: currentWorkflowInstance], view: 'opportunityLayout15'
        } else if (opportunityLayout)
        {
            if (code == '51' && currentRole && currentRole?.authority?.name == "Approval")
            {
                flash.message = "请重新进行房产询值，重查大数据，重做产调"
            }

            respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                         opportunityContacts: opportunityContacts, transactionRecords: transactionRecords, borrowers: borrowers, notarizationsList: notarizationsList,
                                         activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails,
                                         canSpecialApproval : canSpecialApproval, user: user, houses: houses, billsItems: billsItems, canQueryPrice: canQueryPrice, opportunityComments: opportunityComments, canCreditReportShow: canCreditReportShow, canAttachmentsShow: canAttachmentsShow, canPhotosShow: canPhotosShow, canLoanReceiptShow: canLoanReceiptShow, canInterestEdit: canInterestEdit, canbillsShow: canbillsShow, currentWorkflowInstance: currentWorkflowInstance], view: opportunityLayout
        } else
        {
            respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                         opportunityContacts: opportunityContacts, transactionRecords: transactionRecords, borrowers: borrowers, notarizationsList: notarizationsList,
                                         activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails,
                                         canSpecialApproval : canSpecialApproval, user: user, houses: houses, billsItems: billsItems, canQueryPrice: canQueryPrice, opportunityComments: opportunityComments, canCreditReportShow: canCreditReportShow, canAttachmentsShow: canAttachmentsShow, canPhotosShow: canPhotosShow, canLoanReceiptShow: canLoanReceiptShow, canInterestEdit: canInterestEdit, canbillsShow: canbillsShow, currentWorkflowInstance: currentWorkflowInstance]
        }
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO', 'ROLE_POST_LOAN_MANAGER', 'ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER'])
    def historyShow()
    {
        def opportunityHistory = OpportunityHistory.findById(params["id"])
        respond opportunityHistory
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO', 'ROLE_POST_LOAN_MANAGER', 'ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER'])
    def historyShow2(House house)
    {
        def CollateralAuditTrails = HouseAuditTrail.findAllByParent(house)
        respond house, model: [CollateralAuditTrails: CollateralAuditTrails]
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR'])
    def create()
    {
        def contacts = Contact.findAllByType("Agent")
        respond new Opportunity(params), model: [contacts: contacts]
    }

    def getUserAndAccount()
    {
        def contact = Contact.findById(params['contact'])
        def user = contact?.user?.id
        def account = contact?.user?.account?.id
        render([status: "success", user: user, account: account] as JSON)
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    @Transactional
    def save(Opportunity opportunity)
    {
        println opportunity.notarizations
        if (opportunity == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (opportunity.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond opportunity.errors, view: 'create'
            return
        }



        opportunity.save flush: true
        //订单初始化
        opportunityService.initOpportunity(opportunity)
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'opportunity.label',
                    default: 'Opportunity'),
                                                                                opportunity.id])
                redirect opportunity
            }
            '*' { respond opportunity, [status: CREATED] }
        }
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def edit(Opportunity opportunity)
    {
        def flag = params['flag']
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            respond opportunity, view: 'administratorEdit'
        } else if (opportunity?.status == "Pending")
        {

            def stage = opportunity?.stage
            def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")

            if (opportunityRole && opportunityRole?.authority?.name != "Read")
            {
                respond opportunity, model: [flag: flag]
            } else
            {
                flash.message = message(code: 'opportunity.edit.permission.denied')
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id, flag: flag])
                return
            }
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO', 'ROLE_POST_LOAN_MANAGER', 'ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER'])
    def edit01(Opportunity opportunity)
    {
        def flag = params['flag']
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            respond opportunity, view: 'opportunityLayoutEdit15'
        } else if (opportunity?.status == "Pending")
        {

            def stage = opportunity?.stage
            def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")

            if (opportunityRole && opportunityRole?.authority?.name != "Read")
            {
                respond opportunity, model: [flag: flag], view: 'opportunityLayoutEdit16'
            } else
            {
                flash.message = message(code: 'opportunity.edit.permission.denied')
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id, flag: flag])
                return
            }
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def opportunityLayout18(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunity?.status == "Pending")
        {
            if (opportunityRole && opportunityRole?.authority?.name != "Read")
            {
                def history
                if (opportunity && opportunity?.serialNumber)
                {
                    history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
                }
                def code = opportunity?.stage?.code
                def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
                def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


                def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
                def opportunityStage = OpportunityStage.findByCode("38")

                //                def creditReport = CreditReport.findAllByOpportunity(opportunity)
                def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
                //        def liquidityRiskReport = LiquidityRiskReport.findAll("from LiquidityRiskReport where opportunity.id = ${opportunity?.id} order by createdDate ASC")
                def activities = Activity.findAllByOpportunity(opportunity)

                def currentProgress = 0
                def totalProgress = 0
                def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
                def progressPercent
                def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

                def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
                def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")

                def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
                def subUsers = []
                def reportings
                if (currentRole?.authority?.name == 'Approval')
                {
                    reportings = Reporting.findAllByManager(user)
                    reportings?.each {
                        subUsers.add(it?.user)
                    }
                }
                respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                             //                    creditReport: creditReport,
                                             opportunityContacts: opportunityContacts,
                                             activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, houses: houses]
            } else
            {
                flash.message = message(code: 'opportunity.edit.permission.denied')
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
                return
            }
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }

    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def opportunityLayout21(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunity?.status == "Pending")
        {
            def history
            if (opportunity && opportunity?.serialNumber)
            {
                history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
            }
            def code = opportunity?.stage?.code
            def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
            def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


            def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
            def opportunityStage = OpportunityStage.findByCode("38")

            def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
            def activities = Activity.findAllByOpportunity(opportunity)

            def currentProgress = 0
            def totalProgress = 0
            def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
            def progressPercent
            def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

            def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
            def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")

            def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
            def subUsers = []
            def reportings
            if (currentRole?.authority?.name == 'Approval')
            {
                reportings = Reporting.findAllByManager(user)
                reportings?.each {
                    subUsers.add(it?.user)
                }
            }

            def canQueryPrice = true

            def regionalRiskManageStage = OpportunityStage.findByCode("08")


            def canAttachmentsShow = false
            if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_COMPLIANCE_MANAGER")))
            {
                canAttachmentsShow = true
            } else if (currentRole?.authority?.name == 'Approval')
            {
                canAttachmentsShow = true
            }
            def canCreditReportShow = false
            if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_BRANCH_GENERAL_MANAGER")))
            {
                canCreditReportShow = true
            } else if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_COMPLIANCE_MANAGER")))
            {
                if (opportunity?.stage?.code in ["08", "21", "50", "19", "41", "49", "09"])
                {
                    canCreditReportShow = true
                }
            } else if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_BRANCH_OFFICE_RISK_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_HEAD_OFFICE_RISK_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_GENERAL_RISK_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_CUSTOMER_SERVICE_REPRESENTATIVE")))
            {
                if (currentRole?.authority?.name == 'Approval')
                {
                    canCreditReportShow = true
                }
            }
            def canInterestEdit = true
            def loanCompletionStage = OpportunityStage.findByCode("10")

            respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                         opportunityContacts: opportunityContacts,
                                         activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails,
                                         houses             : houses, canQueryPrice: canQueryPrice, canAttachmentsShow: canAttachmentsShow, canCreditReportShow: canCreditReportShow, canInterestEdit: canInterestEdit]
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }

    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-7-10
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def opportunityLayout27(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunity?.status == "Pending")
        {
            def history
            if (opportunity && opportunity?.serialNumber)
            {
                history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = ? order by modifiedDate desc", [opportunity?.serialNumber])
            }
            def code = opportunity?.stage?.code
            def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
            def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


            def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
            def opportunityStage = OpportunityStage.findByCode("38")

            def opportunityContacts = OpportunityContact.findAll("from OpportunityContact where opportunity.id = ${opportunity.id} order by type.id")
            def activities = Activity.findAllByOpportunity(opportunity)

            def currentProgress = 0
            def totalProgress = 0
            def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
            def progressPercent
            def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

            def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
            def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")

            def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
            def subUsers = []
            def reportings
            if (currentRole?.authority?.name == 'Approval')
            {
                reportings = Reporting.findAllByManager(user)
                reportings?.each {
                    subUsers.add(it?.user)
                }
            }

            def canQueryPrice = true

            def regionalRiskManageStage = OpportunityStage.findByCode("08")


            def canAttachmentsShow = false
            if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_COMPLIANCE_MANAGER")))
            {
                canAttachmentsShow = true
            } else if (currentRole?.authority?.name == 'Approval')
            {
                canAttachmentsShow = true
            }
            def canCreditReportShow = false
            if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_BRANCH_GENERAL_MANAGER")))
            {
                canCreditReportShow = true
            } else if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_COMPLIANCE_MANAGER")))
            {
                if (opportunity?.stage?.code in ["08", "21", "50", "19", "41", "49", "09"])
                {
                    canCreditReportShow = true
                }
            } else if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_BRANCH_OFFICE_RISK_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_HEAD_OFFICE_RISK_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_GENERAL_RISK_MANAGER")) || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_CUSTOMER_SERVICE_REPRESENTATIVE")))
            {
                if (currentRole?.authority?.name == 'Approval')
                {
                    canCreditReportShow = true
                }
            }
            def canInterestEdit = true
            def loanCompletionStage = OpportunityStage.findByCode("10")

            respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                         //                    creditReport: creditReport,
                                         opportunityContacts: opportunityContacts,
                                         activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails,
                                         houses             : houses, canQueryPrice: canQueryPrice, canAttachmentsShow: canAttachmentsShow, canCreditReportShow: canCreditReportShow, canInterestEdit: canInterestEdit]
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }

    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def postLoanManager05(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunity?.status == "Pending")
        {
            if (opportunityRole && opportunityRole?.authority?.name != "Read")
            {
                def history
                if (opportunity && opportunity?.serialNumber)
                {
                    history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
                }
                def code = opportunity?.stage?.code
                def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
                def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


                def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
                def opportunityStage = OpportunityStage.findByCode("38")

                def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
                def activities = Activity.findAllByOpportunity(opportunity)

                def currentProgress = 0
                def totalProgress = 0
                def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
                def progressPercent
                def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

                def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
                def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")

                def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
                def subUsers = []
                def reportings
                if (currentRole?.authority?.name == 'Approval')
                {
                    reportings = Reporting.findAllByManager(user)
                    reportings?.each {
                        subUsers.add(it?.user)
                    }
                }
                respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                             //                    creditReport: creditReport,
                                             opportunityContacts: opportunityContacts,
                                             activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, houses: houses]
            } else
            {
                flash.message = message(code: 'opportunity.edit.permission.denied')
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
                return
            }
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }

    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def postLoanManager07(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def history
        if (opportunity && opportunity?.serialNumber)
        {
            history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
        }
        def code = opportunity?.stage?.code
        def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
        def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


        def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
        def opportunityStage = OpportunityStage.findByCode("38")

        def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
        def activities = Activity.findAllByOpportunity(opportunity)

        def currentProgress = 0
        def totalProgress = 0
        def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
        def progressPercent
        def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

        def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)

        def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        def subUsers = []
        def reportings
        if (currentRole?.authority?.name == 'Approval')
        {
            reportings = Reporting.findAllByManager(user)
            reportings?.each {
                subUsers.add(it?.user)
            }
        }

        if (totalProgress > 0)
        {
            progressPercent = currentProgress / totalProgress
        } else
        {
            progressPercent = 0
        }

        def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")
        if (houses?.size() == 1)
        {
            def house = house.findByOpportunity(opportunity)
            if (!house?.propertySerialNumber && opportunity?.propertySerialNumber)
            {
                house.propertySerialNumber = opportunity?.propertySerialNumber
            }
            if (!house?.firstMortgageAmount && opportunity?.firstMortgageAmount)
            {
                house.firstMortgageAmount = opportunity?.firstMortgageAmount
            }
            if (!house?.secondMortgageAmount && opportunity?.secondMortgageAmount)
            {
                house.secondMortgageAmount = opportunity?.secondMortgageAmount
            }
            if (!house?.mortgageType && opportunity?.mortgageType)
            {
                house.mortgageType = opportunity?.mortgageType
            }
            if (!house?.typeOfFirstMortgage && opportunity?.typeOfFirstMortgage)
            {
                house.typeOfFirstMortgage = opportunity?.typeOfFirstMortgage
            }
            house.save flush: true
        }
        def canSpecialApproval = false
        def specialApprovalAttachments = Attachments.findByOpportunityAndType(opportunity, AttachmentType.findByName('特批签呈'))
        if (specialApprovalAttachments && opportunity?.status == 'Failed' && currentRole?.authority?.name == 'Approval')
        {
            if (!(opportunity?.subtype))
            {
                canSpecialApproval = true
            } else if (opportunity?.subtype?.name == '正常审批')
            {
                canSpecialApproval = true
            }
        }
        def opportunityWorkflows = []
        def territory = opportunity?.territory
        if (!territory)
        {
            territory = TerritoryAccount.findByAccount(opportunity?.account)?.territory
        }
        def territoryOpportunityWorkflows = TerritoryWorkflow.findAllByTerritory(territory)
        territoryOpportunityWorkflows?.each {
            opportunityWorkflows.add(it?.workflow)
        }


        respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                     opportunityContacts: opportunityContacts,
                                     activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, canSpecialApproval: canSpecialApproval, user: user, houses: houses]

    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def postLoanManager08(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def history
        if (opportunity && opportunity?.serialNumber)
        {
            history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
        }
        def code = opportunity?.stage?.code
        def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
        def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


        def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
        def opportunityStage = OpportunityStage.findByCode("38")

        def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
        def activities = Activity.findAllByOpportunity(opportunity)

        def currentProgress = 0
        def totalProgress = 0
        def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
        def progressPercent
        def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

        def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)

        def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        def subUsers = []
        def reportings
        if (currentRole?.authority?.name == 'Approval')
        {
            reportings = Reporting.findAllByManager(user)
            reportings?.each {
                subUsers.add(it?.user)
            }
        }

        if (totalProgress > 0)
        {
            progressPercent = currentProgress / totalProgress
        } else
        {
            progressPercent = 0
        }

        def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")
        if (houses?.size() == 1)
        {
            def house = house.findByOpportunity(opportunity)
            if (!house?.propertySerialNumber && opportunity?.propertySerialNumber)
            {
                house.propertySerialNumber = opportunity?.propertySerialNumber
            }
            if (!house?.firstMortgageAmount && opportunity?.firstMortgageAmount)
            {
                house.firstMortgageAmount = opportunity?.firstMortgageAmount
            }
            if (!house?.secondMortgageAmount && opportunity?.secondMortgageAmount)
            {
                house.secondMortgageAmount = opportunity?.secondMortgageAmount
            }
            if (!house?.mortgageType && opportunity?.mortgageType)
            {
                house.mortgageType = opportunity?.mortgageType
            }
            if (!house?.typeOfFirstMortgage && opportunity?.typeOfFirstMortgage)
            {
                house.typeOfFirstMortgage = opportunity?.typeOfFirstMortgage
            }
            house.save flush: true
        }
        def canSpecialApproval = false
        def specialApprovalAttachments = Attachments.findByOpportunityAndType(opportunity, AttachmentType.findByName('特批签呈'))
        if (specialApprovalAttachments && opportunity?.status == 'Failed' && currentRole?.authority?.name == 'Approval')
        {
            if (!(opportunity?.subtype))
            {
                canSpecialApproval = true
            } else if (opportunity?.subtype?.name == '正常审批')
            {
                canSpecialApproval = true
            }
        }
        def opportunityWorkflows = []
        def territory = opportunity?.territory
        if (!territory)
        {
            territory = TerritoryAccount.findByAccount(opportunity?.account)?.territory
        }
        def territoryOpportunityWorkflows = TerritoryWorkflow.findAllByTerritory(territory)
        territoryOpportunityWorkflows?.each {
            opportunityWorkflows.add(it?.workflow)
        }

        respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                     opportunityContacts: opportunityContacts,
                                     activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, canSpecialApproval: canSpecialApproval, user: user, houses: houses]

    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def postLoanManagerEdit03(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunity?.status == "Pending")
        {
            if (opportunityRole && opportunityRole?.authority?.name != "Read")
            {
                def history
                if (opportunity && opportunity?.serialNumber)
                {
                    history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
                }
                def code = opportunity?.stage?.code
                def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
                def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


                def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
                def opportunityStage = OpportunityStage.findByCode("38")

                def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
                def activities = Activity.findAllByOpportunity(opportunity)

                def currentProgress = 0
                def totalProgress = 0
                def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
                def progressPercent
                def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

                def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
                def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")

                def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
                def subUsers = []
                def reportings
                if (currentRole?.authority?.name == 'Approval')
                {
                    reportings = Reporting.findAllByManager(user)
                    reportings?.each {
                        subUsers.add(it?.user)
                    }
                }
                respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                             opportunityContacts: opportunityContacts,
                                             activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, houses: houses]
            } else
            {
                flash.message = message(code: 'opportunity.edit.permission.denied')
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
                return
            }
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }

    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def postLoanManagerEdit09(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunity?.status == "Pending")
        {
            if (opportunityRole && opportunityRole?.authority?.name != "Read")
            {
                def history
                if (opportunity && opportunity?.serialNumber)
                {
                    history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
                }
                def code = opportunity?.stage?.code
                def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
                def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


                def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
                def opportunityStage = OpportunityStage.findByCode("38")

                def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
                def activities = Activity.findAllByOpportunity(opportunity)

                def currentProgress = 0
                def totalProgress = 0
                def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
                def progressPercent
                def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

                def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
                def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")

                def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
                def subUsers = []
                def reportings
                if (currentRole?.authority?.name == 'Approval')
                {
                    reportings = Reporting.findAllByManager(user)
                    reportings?.each {
                        subUsers.add(it?.user)
                    }
                }
                respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                             opportunityContacts: opportunityContacts,
                                             activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, houses: houses]
            } else
            {
                flash.message = message(code: 'opportunity.edit.permission.denied')
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
                return
            }
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }

    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def postLoanManagerEdit10(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunity?.status == "Pending")
        {
            if (opportunityRole && opportunityRole?.authority?.name != "Read")
            {
                def history
                if (opportunity && opportunity?.serialNumber)
                {
                    history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
                }
                def code = opportunity?.stage?.code
                def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
                def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


                def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
                def opportunityStage = OpportunityStage.findByCode("38")

                def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
                def activities = Activity.findAllByOpportunity(opportunity)

                def currentProgress = 0
                def totalProgress = 0
                def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
                def progressPercent
                def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

                def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
                def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")

                def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
                def subUsers = []
                def reportings
                if (currentRole?.authority?.name == 'Approval')
                {
                    reportings = Reporting.findAllByManager(user)
                    reportings?.each {
                        subUsers.add(it?.user)
                    }
                }
                respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                             opportunityContacts: opportunityContacts,
                                             activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, houses: houses]
            } else
            {
                flash.message = message(code: 'opportunity.edit.permission.denied')
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
                return
            }
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }

    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def postLoanManagerEdit11(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunity?.status == "Pending")
        {
            if (opportunityRole && opportunityRole?.authority?.name != "Read")
            {
                def history
                if (opportunity && opportunity?.serialNumber)
                {
                    history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
                }
                def code = opportunity?.stage?.code
                def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
                def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


                def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
                def opportunityStage = OpportunityStage.findByCode("38")

                def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
                def activities = Activity.findAllByOpportunity(opportunity)

                def currentProgress = 0
                def totalProgress = 0
                def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
                def progressPercent
                def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")

                def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)
                def houses = House.findAll("from House where opportunity.id = ${opportunity?.id} order by id asc")

                def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
                def subUsers = []
                def reportings
                if (currentRole?.authority?.name == 'Approval')
                {
                    reportings = Reporting.findAllByManager(user)
                    reportings?.each {
                        subUsers.add(it?.user)
                    }
                }
                respond opportunity, model: [history            : history, opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows,
                                             opportunityContacts: opportunityContacts,
                                             activities         : activities, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys, bankAccounts: bankAccounts, subUsers: subUsers, CollateralAuditTrails: CollateralAuditTrails, houses: houses]
            } else
            {
                flash.message = message(code: 'opportunity.edit.permission.denied')
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
                return
            }
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }

    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Transactional
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    def specialApprove(Opportunity opportunity)
    {
        opportunity.subtype = OpportunitySubtype.findByName("特殊审批")
        opportunity.lastAction = OpportunityAction.findByName("特批")
        opportunity.status = 'Pending'
        opportunity.save flush: true

        flash.message = "特批成功"
        redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
        return
    }

    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    @Transactional
    def initOpportunityProduct(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def map = [:]
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunityRole && opportunityRole?.authority?.name == "Approval")
        {
            def opportunityProductList = OpportunityProduct.findAllByOpportunity(opportunity)
            if (opportunityProductList && opportunityProductList.size() > 0)
            {
                for (
                    def opportunityProduct :
                        opportunityProductList)
                {
                    opportunityProduct.delete flush: true
                }
            }

            map = opportunityService.initProductInterest(opportunity)
            println map['flag']
            if (map['flag'])
            {
                redirect(controller: "opportunity", action: "refreshOpportunityProduct", params: [id: opportunity.id])
                return
            } else
            {
                def message = map['message']
                if (message)
                {
                    flash.message = map['message']
                }
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
                return
            }
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }
    }

    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    @Transactional
    def refreshOpportunityProduct(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunityRole && opportunityRole?.authority?.name == "Approval")
        {
            def opportunityProductList = OpportunityProduct.findAllByProductAndOpportunity(opportunity?.productAccount, opportunity)
            opportunity.monthlyInterest = 0
            if (opportunityProductList && opportunityProductList.size() > 0)
            {
                println opportunityProductList
                for (
                    def opportunityProduct :
                        opportunityProductList)
                {
                    if (opportunityProduct?.productInterestType?.name == "基本费率" || opportunityProduct?.productInterestType?.name == "信用调整" || opportunityProduct?.productInterestType?.name == "二抵加收费率" || opportunityProduct?.productInterestType?.name == "郊县" || opportunityProduct?.productInterestType?.name == "大头小尾" || opportunityProduct?.productInterestType?.name == "老人房（65周岁以上）")
                    {
                        opportunity.monthlyInterest += Math.round(opportunityProduct?.rate * 100 * 100) / 100
                        //月息=基本费率+二押费率（二押）+信用调整+郊县+大头小尾+老人房（65周岁以上）
                    }
                    if (opportunityProduct?.productInterestType?.name == "渠道返费费率")
                    {
                        opportunity.commissionRate = Math.round(opportunityProduct?.rate * 100 * 100 / opportunity.loanDuration) / 100
                        //渠道服务费
                    }
                    if (opportunityProduct?.productInterestType?.name == "服务费费率")
                    {
                        //借款服务费
                        opportunity.serviceCharge = Math.round(opportunityProduct?.rate * 100 * 100) / 100
                    }
                }
                opportunity.save flush: true
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
                return
            } else
            {
                flash.message = "请先进行计算息费"
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
                return
            }
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }
    }

    @Secured(['ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    @Transactional
    def tongdun(Opportunity opportunity)
    {
        println "同盾评估"
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)

        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunityRole && opportunityRole?.authority?.name == "Approval")
        {
            def provider = CreditReportProvider.findByCode("TONGDUN")
            def contactName = []
            def contactIdNumber = []
            def contactNameAndNumber = []
            def contactId = []
            def messageJudge = []
            opportunity.contacts.each {
                if (it?.contact?.fullName)
                {
                    if (it?.contact?.idNumber)
                    {
                        Boolean flag = contactService.verifyIdNumber(it?.contact?.idNumber)
                        if (flag && it?.contact?.fullName.matches(/^([\u2190-\u9fff]{1,20}|[a-zA-Z\.\s]{1,20})/))
                        {
                            creditReportService.generateReport(provider, opportunity, it?.contact)
                        } else
                        {
                            messageJudge.add "姓名：" + it?.contact?.fullName + "或身份证号：" + it?.contact?.idNumber + "的校验不通过"
                        }
                    } else
                    {
                        contactName.add it?.type?.name + "的身份证号为空"
                    }
                } else
                {
                    if (it?.contact?.idNumber)
                    {
                        contactIdNumber.add it?.type?.name + "的姓名为空 "
                    } else
                    {
                        if (it?.contact?.cellphone)
                        {
                            contactNameAndNumber.add it?.type?.name + "的身份证号和姓名都为空 "
                        } else
                        {
                            contactId.add it?.type?.name + "的手机号，身份证号，姓名均为空 "
                        }
                    }
                }
            }
            flash.message = ""
            if (contactName)
            {
                flash.message += contactName
            }
            if (contactIdNumber)
            {
                flash.message += contactIdNumber
            }
            if (contactNameAndNumber)
            {
                flash.message += contactNameAndNumber
            }
            if (contactId)
            {
                flash.message += contactId
            }
            if (messageJudge)
            {
                flash.message += messageJudge
            }
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }
    }

    @Secured(['ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    @Transactional
    def bairong(Opportunity opportunity)
    {
        println "百融评估"
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)

        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunityRole && opportunityRole?.authority?.name == "Approval")
        {
            def provider = CreditReportProvider.findByCode("BAIRONG")
            def contactName = []
            def contactIdNumber = []
            def contactNameAndNumber = []
            def contactPhone = []
            def messageJudge = []
            opportunity.contacts.each {
                if (it?.contact?.cellphone && it?.contact?.cellphone?.size() == 11 && it?.contact?.cellphone.matches(/^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$/))
                {
                    if (it?.contact?.fullName)
                    {
                        if (it?.contact?.idNumber)
                        {
                            Boolean flag = contactService.verifyIdNumber(it?.contact?.idNumber)
                            if (flag && it?.contact?.fullName.matches(/^([\u2190-\u9fff]{1,20}|[a-zA-Z\.\s]{1,20})/))
                            {
                                creditReportService.generateReport(provider, opportunity, it?.contact)
                            } else
                            {
                                messageJudge.add "姓名：" + it?.contact?.fullName + "或身份证号：" + it?.contact?.idNumber + "的校验不通过"
                            }
                        } else
                        {
                            contactName.add it?.type?.name + "的身份证号为空"
                        }
                    } else
                    {
                        if (it?.contact?.idNumber)
                        {
                            contactIdNumber.add it?.type?.name + "的姓名为空 "
                        } else
                        {
                            contactNameAndNumber.add it?.type?.name + "的身份证号和姓名都为空 "
                        }
                    }
                } else
                {
                    contactPhone.add it?.type?.name + "手机号为空或手机号校验未通过"
                }
            }
            flash.message = ""
            if (contactName)
            {
                flash.message += contactName
            }
            if (contactIdNumber)
            {
                flash.message += contactIdNumber
            }
            if (contactNameAndNumber)
            {
                flash.message += contactNameAndNumber
            }
            if (messageJudge)
            {
                flash.message += messageJudge
            }
            if (contactPhone)
            {
                flash.message += contactPhone
            }
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    @Transactional
    def update(Opportunity opportunity)
    {
        if (opportunity == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (opportunity.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond opportunity.errors, view: 'edit'
            return
        }
        if (params["actuaDate"])
        {
            opportunity.actuaRepaymentDate = new SimpleDateFormat("yyyy-MM-dd").parse(params["actuaDate"])
            if (opportunity.parent)
            {
                opportunity.parent.actuaRepaymentDate = opportunity?.actuaRepaymentDate
                opportunity.parent.save flush: true
            }
        }
        if (opportunity.notarizations)
        {
            def last = opportunity.notarizations.substring(opportunity.notarizations.length() - 1, opportunity.notarizations.length())
            if (last == ",")
            {
                opportunity.notarizations = opportunity.notarizations.substring(0, opportunity.notarizations.lastIndexOf(","))
            }
        }
        def pro = ProductAccount.findByAccountAndProduct(opportunity?.account, opportunity?.product)
        opportunity.productAccount = pro
        def username = springSecurityService.getPrincipal().username
        opportunity.modifiedBy = User.findByUsername(username)
        opportunity.modifiedDate = new Date()
        /*//修改页面金额单位为万元
        opportunity.actualLoanAmount = opportunity?.actualLoanAmount * 10000
        opportunity.actualAmountOfCredit = opportunity?.actualAmountOfCredit * 10000
        opportunity.loanAmount = opportunity?.loanAmount * 10000
        opportunity.requestedAmount = opportunity?.requestedAmount * 10000
        opportunity.commission = opportunity?.commission * 10000
        opportunity.maximumAmountOfCredit = opportunity?.maximumAmountOfCredit * 10000*/
        opportunityService.backup(opportunity)

        opportunity.save flush: true
        redirect(controller: "opportunity", action: "show", id: opportunity.id)
    }

    /**
     * @Description
     * @Author bigyuan
     * @Return
     * @DateTime 2017/9/18 10:57
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    @Transactional
    def ajaxUpd()
    {
        def actuaRepaymentDate = params['actuaRepaymentDate']
        if (actuaRepaymentDate)
        {
            actuaRepaymentDate = new SimpleDateFormat("yyyy-MM-dd").parse(actuaRepaymentDate)
        }

        if (new Date() < actuaRepaymentDate)
        {
            render([status: "success"] as JSON)

            return

        } else
        {
            render([status: "fail", errMsg: "约定还款日必须大于当天日期！"] as JSON)
            return
        }

    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO', 'ROLE_POST_LOAN_MANAGER', 'ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER'])
    @Transactional
    def ajaxUpdate(Opportunity opportunity)
    {
        // println "params:" + params
        if (params["level"])
        {
            //def contact = Contact.findByIdNumberAndType(opportunity.idNumber, "Client");
            def contact = Contact.findById(opportunity?.lender?.id);
            if (contact)
            {
                def level = ContactLevel.findByName(params["level"])
                contact.level = level
                contact.save flush: true
            }
        }
        if (!params['notarizationMatters'])
        {
            opportunity.notarizationMatters = null
        }
        if (!params['signedDocuments'])
        {
            opportunity.signedDocuments = null
        }
        if (!params['mortgageMaterials'])
        {
            opportunity.mortgageMaterials = null
        }

        def username = springSecurityService.getPrincipal().username
        opportunity.modifiedBy = User.findByUsername(username)
        opportunity.modifiedDate = new Date()
        /*opportunity.actualAmountOfCredit = opportunity.actualAmountOfCredit*10000
        opportunity.commission = opportunity.commission*10000*/
        opportunityService.backup(opportunity)

        if (opportunity.validate())
        {
            opportunity.save flush: true
            render([status: "success"] as JSON)
            return
        } else
        {
            render([status: "fail", errorMessage: opportunity.errors] as JSON)
            return
        }
    }

    @Secured(['ROLE_EVENT_CONFIGURATION', 'ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO', 'ROLE_POST_LOAN_MANAGER', 'ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER'])
    @Transactional
    def ajaxUpdate1(Opportunity opportunity)
    {
        // println "params:" + params
        if (params["level"])
        {
            //def contact = Contact.findByIdNumberAndType(opportunity.idNumber, "Client");
            def contact = Contact.findById(opportunity?.lender?.id);
            if (contact)
            {
                def level = ContactLevel.findByName(params["level"])
                contact.level = level
                contact.save flush: true
            }
        }

        def username = springSecurityService.getPrincipal().username
        opportunity.modifiedBy = User.findByUsername(username)
        opportunity.modifiedDate = new Date()
//        opportunity.actualAmountOfCredit = opportunity.actualAmountOfCredit*10000
        opportunityService.backup(opportunity)

        if (opportunity.validate())
        {
            opportunity.save flush: true
            render([status: "success"] as JSON)
            return
        } else
        {
            render([status: "fail", errorMessage: opportunity.errors] as JSON)
            return
        }
    }

    @Secured(['ROLE_ADMINISTRATOR'])
    @Transactional
    def delete(Opportunity opportunity)
    {

        if (opportunity == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        opportunity.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'opportunity.label',
                    default: 'Opportunity'),
                                                                                opportunity.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    @Secured('permitAll')
    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'opportunity.label',
                    default: 'Opportunity'),
                                                                                  params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_PRODUCT_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    @Transactional
    def showHelp(Document document)
    {
        respond document
    }

    @Secured(['ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_PRODUCT_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO', 'ROLE_POST_LOAN_MANAGER', 'ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER'])
    @Transactional
    def prepareRenewal(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def newOpportunity = new Opportunity()
        newOpportunity.parent = opportunity
        newOpportunity.type = OpportunityType.findByCode("20")

        newOpportunity.user = opportunity?.user
        newOpportunity.account = opportunity?.account
        newOpportunity.fullName = opportunity?.fullName
        newOpportunity.unitPrice = opportunity?.unitPrice
        newOpportunity.loanAmount = opportunity?.loanAmount
        newOpportunity.product = opportunity?.product
        newOpportunity.mortgageType = opportunity?.mortgageType
        newOpportunity.firstMortgageAmount = opportunity?.firstMortgageAmount
        newOpportunity.secondMortgageAmount = opportunity?.secondMortgageAmount
        newOpportunity.typeOfFirstMortgage = opportunity?.typeOfFirstMortgage

        newOpportunity.save flush: true
        respond newOpportunity, view: 'renewal'
        return
    }

    @Secured(['ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO', 'ROLE_POST_LOAN_MANAGER', 'ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER'])
    @Transactional
    def renewal(Opportunity opportunity)
    {
        if (opportunity == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (opportunity.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond opportunity.errors, view: 'renewal'
            return
        }

        def opportunityStage = OpportunityStage.findByCode("51")
        opportunity.stage = opportunityStage
        opportunity.save flush: true
        opportunityService.initOpportunity(opportunity)

        //copy
        def parent = opportunity?.parent
        opportunity.contact = parent?.contact
        opportunity.lender = parent?.lender
        opportunity.productAccount = parent?.productAccount
        def houses = parent?.houses
        houses?.each {
            def house = new House()
            house.opportunity = opportunity
            house.externalId = it?.externalId
            house.city = it?.city
            house.district = it?.district
            house.projectName = it?.projectName
            house.address = it?.address
            house.orientation = it?.orientation
            house.area = it?.area
            house.building = it?.building
            house.unit = it?.unit
            house.roomNumber = it?.roomNumber
            house.floor = it?.floor
            house.totalFloor = it?.totalFloor
            house.assetType = it?.assetType
            house.houseType = it?.houseType
            house.specialFactors = it?.specialFactors
            house.status = 'Pending'
            house.unitPrice = 0
            house.totalPrice = 0
            house.requestStartTime = null
            house.requestEndTime = null
            house.save flush: true
        }

        def parentAutitTrails = HouseAuditTrail.findAllByOpportunity(parent)
        parentAutitTrails?.each {
            def houseAuditTrail = new HouseAuditTrail()
            houseAuditTrail.opportunity = opportunity
            houseAuditTrail.unitPrice = it?.unitPrice
            houseAuditTrail.totalPrice = it?.totalPrice
            houseAuditTrail.createdDate = it?.createdDate
            houseAuditTrail.save flush: true
        }

        def parentContacts = OpportunityContact.findAllByOpportunity(parent)
        parentContacts?.each {
            def opportunityContact = new OpportunityContact()
            opportunityContact.opportunity = opportunity
            opportunityContact.contact = it?.contact
            opportunityContact.type = it?.type
            opportunityContact.save flush: true
        }

        def parentBankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")
        parentBankAccounts?.each {
            def bankAccount = new OpportunityBankAccount()
            bankAccount.opportunity = opportunity
            bankAccount.name = it?.name
            bankAccount.type = it?.type
            bankAccount.bank = it?.bank
            bankAccount.bankBranch = it?.bankBranch
            bankAccount.bankAddress = it?.bankAddress
            bankAccount.bankAccount = it?.bankAccount
            bankAccount.idNumber = it?.idNumber
            bankAccount.save flush: true
        }

        def parentAttachments = Attachments.findAllByOpportunity(parent)
        parentAttachments?.each {
            def attachment = new Attachments()
            attachment.opportunity = opportunity
            attachment.activity = it?.activity
            attachment.contact = it?.contact
            attachment.type = it?.type
            attachment.fileName = it?.fileName
            attachment.description = it?.description
            attachment.createdDate = it?.createdDate
            attachment.modifiedDate = it?.modifiedDate
            attachment.save flush: true
        }

        def parentFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(parent)
        parentFlexFieldCategorys?.each {
            def flexFieldCategory1 = new OpportunityFlexFieldCategory()
            flexFieldCategory1.opportunity = opportunity
            flexFieldCategory1.flexFieldCategory = it?.flexFieldCategory
            flexFieldCategory1.save flush: true

            it?.fields?.each {
                def flexField = new OpportunityFlexField()
                flexField.category = flexFieldCategory1
                flexField.name = it?.name
                flexField.description = it?.description
                flexField.dataType = it?.dataType
                flexField.defaultValue = it?.defaultValue
                flexField.value = it?.value
                flexField.displayOrder = it?.displayOrder
                flexField.valueConstraints = it?.valueConstraints
                flexField.save flush: true

                it?.values?.each {
                    def flexValue = new OpportunityFlexFieldValue()
                    flexValue.field = flexField
                    flexValue.value = it?.value
                    flexValue.displayOrder = it?.displayOrder
                    flexValue.save flush: true
                }
            }

        }

        def parentTeams = OpportunityTeam.findAllByOpportunity(parent)
        parentTeams?.each {
            def opportunityTeam = new OpportunityTeam()
            opportunityTeam.opportunity = opportunity
            opportunityTeam.user = it?.user
            opportunityTeam.createdDate = it?.createdDate
            opportunityTeam.modifiedDate = it?.modifiedDate
            opportunityTeam.save flush: true
        }
        opportunity.save flush: true

        def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
        def bankAccounts = OpportunityBankAccount.findAll("from OpportunityBankAccount where opportunity.id = ${opportunity?.id} order by type desc")
        def opportunityProduct = OpportunityProduct.findAllByOpportunityAndProduct(opportunity, opportunity?.productAccount)
        def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
        def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)


        def CollateralAuditTrails = HouseAuditTrail.findAllByOpportunity(opportunity)

        def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
        def activities = Activity.findAllByOpportunity(opportunity)
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)

        def currentProgress = 0
        def totalProgress = 0
        def progressPercent
        def currentRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        def subUsers = []
        def reportings
        if (currentRole?.authority?.name == 'Approval')
        {
            reportings = Reporting.findAllByManager(user)
            reportings?.each {
                subUsers.add(it?.user)
            }
        }

        if (totalProgress > 0)
        {
            progressPercent = currentProgress / totalProgress
        } else
        {
            progressPercent = 0
        }

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'opportunity.label',
                    default: 'Opportunity'),
                                                                                opportunity.id])
                respond opportunity, model: [opportunityContacts: opportunityContacts, bankAccounts: bankAccounts, opportunityProduct: opportunityProduct, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys,
                                             opportunityTeams   : opportunityTeams, CollateralAuditTrails: CollateralAuditTrails, opportunityFlows: opportunityFlows,
                                             activities         : activities], view: 'opportunityLayout04'
            }
            '*' { respond opportunity, [status: CREATED] }
        }
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_PRODUCT_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO'])
    @Transactional
    def opportunityEdit01(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")
        if (opportunityRole && opportunityRole?.authority?.name == "Approval")
        {
            respond opportunity, model: [user: user]
            return
        } else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }

    }

    def calculateCommission()
    {
        def actualAmountOfCredit = params["actualAmountOfCredit"]
        def commissionRate = params["commissionRate"]
        def actualLoanDuration = params["actualLoanDuration"]
        def commissionPaymentMethod = params["commissionPaymentMethod"]
        def method = CommissionPaymentMethod.findById(commissionPaymentMethod)?.name
        def commission = 0
        if (actualAmountOfCredit && commissionRate)
        {
            commission = actualAmountOfCredit?.toDouble() * commissionRate?.toDouble() / 100
        }
        if (method == '月月返')
        {
            if (actualLoanDuration)
            {
                commission = commission * actualLoanDuration?.toDouble()
            }
        }
        commission = Math.round(commission * 100 * 100 * 100) / 100 / 100 / 100
        render([status: "success", commission: commission] as JSON)
    }

    @Secured(['ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPLIANCE_MANAGER'])
    @Transactional
    def changeOpportunityStage()
    {
        def opportunity = Opportunity.findById(params['opportunity'])
        def opportunityStage = OpportunityStage.findById(params['opportunityStage'])
        def memo = params['memo']
        if (memo)
        {
            opportunity.memo = memo
        }
        opportunity.stage = opportunityStage
        opportunity.save(flush: true)
        opportunityNotificationService.sendNotification(opportunity)
        redirect controller: "opportunity", action: "show", method: "GET", id: opportunity?.id
        return
    }

    @Secured(['ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPLIANCE_MANAGER'])
    @Transactional
    def rollbackOpportunityStage()
    {
        def opportunity = Opportunity.findById(params['opportunity'])
        def opportunityStage = OpportunityStage.findByName("结清申请已提交")
        if (opportunity && opportunityStage)
        {
            opportunity.stage = opportunityStage
            opportunity.save(flush: true)
            opportunityNotificationService.sendNotification(opportunity)
        }
        flash.message = "回退成功！"
        redirect controller: "opportunity", action: "show", method: "GET", id: opportunity?.id
        return
    }

    @Secured(['ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER'])
    @Transactional
    def changeOpportunityStatus()
    {
        def opportunity = Opportunity.findById(params['opportunity'])
        def opportunityStatus = params['opportunityStatus']
        opportunity.status = opportunityStatus
        opportunity.save(flush: true)
        opportunityNotificationService.sendNotification(opportunity)
        redirect controller: "opportunity", action: "show", method: "GET", id: opportunity?.id
        return
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_POST_LOAN_MANAGER', 'ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER'])
    @Transactional
    def preparePostLoan()
    {
        def parentOpportunity = Opportunity.findById(params['parentOpportunity'])
        def type = OpportunityType.findByCode(params['type'])
        def opportunity = new Opportunity()
        opportunity.parent = parentOpportunity
        opportunity.type = type
        opportunity.user = parentOpportunity?.user
        opportunity.account = parentOpportunity?.account
        respond opportunity, view: 'postLoanManager02'
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_POST_LOAN_MANAGER', 'ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER'])
    @Transactional
    def preparePrepayment()
    {
        def parentOpportunity = Opportunity.findById(params['parentOpportunity'])
        def type = OpportunityType.findByCode(params['type'])
        def opportunity = new Opportunity()
        opportunity.parent = parentOpportunity
        opportunity.type = type
        opportunity.user = parentOpportunity?.user
        opportunity.account = parentOpportunity?.account
        respond opportunity, view: 'postLoanManager12'
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['ROLE_POST_LOAN_MANAGER', 'ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER'])
    @Transactional
    def postLoan(Opportunity opportunity)
    {
        if (opportunity == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (opportunity.hasErrors())
        {
            println opportunity.errors
            transactionStatus.setRollbackOnly()
            respond opportunity.errors, view: 'postLoanManager01'
            return
        }
        if (params.actuaDate)
        {
            opportunity.actuaRepaymentDate = new SimpleDateFormat("yyyy-MM-dd").parse(params.actuaDate)
            if (opportunity?.parent)
            {
                opportunity?.parent?.actuaRepaymentDate = opportunity?.actuaRepaymentDate
                opportunity?.parent.save flush: true
            }

        }
        opportunity.contact = opportunity?.parent?.contact
        opportunity.lender = opportunity?.parent?.lender
        opportunity.fullName = opportunity?.parent?.fullName
        opportunity.idNumber = opportunity?.parent?.idNumber
        opportunity.maritalStatus = opportunity?.parent?.maritalStatus
        opportunity.product = opportunity?.parent?.product
        opportunity.interestPaymentMethod = opportunity?.parent?.interestPaymentMethod
        opportunity.monthOfAdvancePaymentOfInterest = opportunity?.parent?.monthOfAdvancePaymentOfInterest
        opportunity.actualAmountOfCredit = opportunity?.parent?.actualAmountOfCredit
        opportunity.actualLoanDuration = opportunity?.parent?.actualLoanDuration
        opportunity.save flush: true
        opportunityService.initOpportunity(opportunity)


        def opportunityFlow = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
        opportunity.stage = opportunityFlow?.stage
        opportunity.save flush: true
        //房产(去价格)、联系人、附件、下户、账户、合同、息费
        def parent = opportunity?.parent
        def houses = House.findAllByOpportunity(parent)
        houses?.each {
            def house = new House()
            house.opportunity = opportunity
            house.assetType = it?.assetType
            house.projectName = it?.projectName
            house.city = it?.city
            house.district = it?.district
            house.address = it?.address
            house.floor = it?.floor
            house.orientation = it?.orientation
            house.area = it?.area
            house.building = it?.building
            house.unit = it?.unit
            house.totalFloor = it?.totalFloor
            house.roomNumber = it?.roomNumber
            house.houseType = it?.houseType
            house.specialFactors = it?.specialFactors
            house.reasonOfPriceAdjustment = it?.reasonOfPriceAdjustment
            house.appliedTotalPrice = it?.appliedTotalPrice
            house.requestStartTime = it?.requestStartTime
            house.requestEndTime = it?.requestEndTime
            house.projectType = it?.projectType
            house.buildTime = it?.buildTime
            house.loanToValue = it?.loanToValue
            house.propertySerialNumber = it?.propertySerialNumber
            house.typeOfFirstMortgage = it?.typeOfFirstMortgage
            house.firstMortgageAmount = it?.firstMortgageAmount
            house.secondMortgageAmount = it?.secondMortgageAmount
            house.mortgageType = it?.mortgageType
            house.region = it?.region
            house.atticArea = it?.atticArea
            house.status = 'Pending'
            if (house.validate())
            {
                house.save flush: true
            } else
            {
                println house.errors
            }
        }
        def opportunityContacts = OpportunityContact.findAllByOpportunity(parent)
        opportunityContacts?.each {
            def opportunityContact = new OpportunityContact()
            opportunityContact.opportunity = opportunity
            opportunityContact.type = it?.type
            opportunityContact.contact = it?.contact
            opportunityContact.connectedContact = it?.connectedContact
            opportunityContact.connectedType = it?.connectedType
            if (opportunityContact.validate())
            {
                opportunityContact.save flush: true
            } else
            {
                println opportunityContact.errors
            }
        }
        def attachments = Attachments.findAllByOpportunity(parent)
        attachments?.each {
            def attachment = new Attachments()
            attachment.opportunity = opportunity
            attachment.type = it?.type
            attachment.fileName = it?.fileName
            attachment.description = it?.description
            attachment.displayOrder = it?.displayOrder
            attachment.activity = it?.activity
            attachment.contact = it?.contact
            if (attachment.validate())
            {
                attachment.save flush: true
            } else
            {
                println attachment.errors
            }
        }
        def activities = Activity.findAllByOpportunity(parent)
        activities?.each {
            def activity = new Activity()
            activity.opportunity = opportunity
            activity.startTime = it?.startTime
            activity.endTime = it?.endTime
            activity.actualStartTime = it?.actualStartTime
            activity.actualEndTime = it?.actualEndTime
            activity.description = it?.description
            activity.type = it?.type
            activity.subtype = it?.subtype
            activity.status = it?.status
            activity.longitude = it?.longitude
            activity.latitude = it?.latitude
            activity.city = it?.city
            activity.address = it?.address
            activity.name = it?.name
            activity.user = it?.user
            activity.contact = it?.contact
            activity.assignedTo = it?.assignedTo
            activity.parent = it?.parent
            if (activity.validate())
            {
                activity.save flush: true
            } else
            {
                println activity.errors
            }
        }
        def opportunityBankAccounts = OpportunityBankAccount.findAllByOpportunity(parent)
        opportunityBankAccounts?.each {
            def opportunityBankAccount = new OpportunityBankAccount()
            opportunityBankAccount.opportunity = opportunity
            opportunityBankAccount.type = it?.type
            opportunityBankAccount.bankAccount = it?.bankAccount
            if (opportunityBankAccount.validate())
            {
                opportunityBankAccount.save flush: true
            } else
            {
                println opportunityBankAccount.errors
            }
        }
        def opportunityContracts = OpportunityContract.findAllByOpportunity(parent)
        opportunityContracts?.each {
            def opportunityContract = new OpportunityContract()
            opportunityContract.opportunity = opportunity
            opportunityContract.contract = it?.contract
            if (opportunityContract.validate())
            {
                opportunityContract.save flush: true
            } else
            {
                println opportunityContract.errors
            }
        }
        def opportunityProducts = OpportunityProduct.findAllByOpportunity(parent)
        opportunityProducts?.each {
            def opportunityProduct = new OpportunityProduct()
            opportunityProduct.opportunity = opportunity
            opportunityProduct.productInterestType = it?.productInterestType
            opportunityProduct.fixedRate = it?.fixedRate
            opportunityProduct.installments = it?.installments
            opportunityProduct.rate = it?.rate
            opportunityProduct.monthes = it?.monthes
            opportunityProduct.firstPayMonthes = it?.firstPayMonthes
            opportunityProduct.product = it?.product
            opportunityProduct.createBy = it?.createBy
            opportunityProduct.modifyBy = it?.modifyBy
            if (opportunityProduct.validate())
            {
                opportunityProduct.save flush: true
            } else
            {
                println opportunityProduct.errors
            }
        }

        def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(parent)
        opportunityFlexFieldCategorys?.each {
            def opportunityFlexFieldCategory = new OpportunityFlexFieldCategory()
            opportunityFlexFieldCategory.opportunity = opportunity
            opportunityFlexFieldCategory.flexFieldCategory = it?.flexFieldCategory
            opportunityFlexFieldCategory.save flush: true

            it?.fields?.each {
                def opportunityflexField = new OpportunityFlexField()
                opportunityflexField.category = opportunityFlexFieldCategory
                opportunityflexField.name = it?.name
                opportunityflexField.description = it?.description
                opportunityflexField.dataType = it?.dataType
                opportunityflexField.defaultValue = it?.defaultValue
                opportunityflexField.value = it?.value
                opportunityflexField.displayOrder = it?.displayOrder
                opportunityflexField.valueConstraints = it?.valueConstraints
                opportunityflexField.save flush: true

                it?.values?.each {
                    def opportunityFlexFieldValue = new OpportunityFlexFieldValue()
                    opportunityFlexFieldValue.field = opportunityflexField
                    opportunityFlexFieldValue.value = it?.value
                    opportunityFlexFieldValue.displayOrder = it?.displayOrder
                    opportunityFlexFieldValue.save flush: true
                }
            }
        }

        redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
        return
    }

    /**
     * @Description ajax
     * @Author bigyuan
     * @Return
     * @DateTime 2017/9/15 13:54
     */
    @Secured(['ROLE_POST_LOAN_MANAGER', 'ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER'])
    @Transactional
    def afterPostLoan()
    {

        def opportunity = Opportunity.findById(params['opportunityId'])
        def actuaRepaymentDate = params['actuaRepaymentDate']
        if (actuaRepaymentDate)
        {
            actuaRepaymentDate = new SimpleDateFormat("yyyy-MM-dd").parse(actuaRepaymentDate)
        }
        def map = [:]
        def sonOpportunity = Opportunity.findAllByParent(opportunity)
        if (sonOpportunity.size() > 0)
        {
            render([status: "fail", errMsg: "结清只能发起一次"] as JSON)
            return
        } else
        {
            if (actuaRepaymentDate > new Date())
            {
                if (opportunity.bills[0].endTime >= actuaRepaymentDate)
                {
                    def interest = OpportunityProduct.findByOpportunityAndProductAndProductInterestType(opportunity, opportunity?.productAccount, ProductInterestType.findByName("早偿违约金"))
                    if (!interest)
                    {
                        render([status: "fail", errMsg: "请添加早偿违约金费率！"] as JSON)
                    } else
                    {
                        render([status: "success"] as JSON)
                    }
                    return
                } else
                {
                    render([status: "success"] as JSON)
                    return
                }
            } else
            {
                render([status: "fail", errMsg: "约定还款日需大于当日！"] as JSON)
                return
            }

        }

    }

    @Secured(['permitAll'])
    @Transactional
    def welcome()
    {
        println "************************* update remote ip ****************************************"

        String ip = request.getHeader("x-forwarded-for")
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("Proxy-Client-IP")
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("WL-Proxy-Client-IP")
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getRemoteAddr()
        }

        println "client ip: " + ip

        if (ip)
        {
            def userName = springSecurityService.getPrincipal().username
            def loginHistory = LoginHistory.find("from LoginHistory where userName = :userName", [userName: userName])
            loginHistory?.ip = ip
            if (loginHistory?.validate())
            {
                loginHistory?.save flush: true
            } else
            {
                println loginHistory?.errors
            }
        }
        return
    }

    /**
     * 外贸预审*/
    @Secured(['permitAll'])
    @Transactional
    def foticAheadSubmit(String id)
    {
        println("foticAheadSubmitfoticAheadSubmitfoticAheadSubmitfoticAheadSubmit");
        println("id" + id);

        foticAheadService.foticAheadSubmit(id);

    }

    /**
     *  中航审批接口调用
     *  */
    @Secured(['permitAll'])
    @Transactional
    def avicAheadSubmit()
    {
        println "aaaaaaaaaaaa"
        def opportunity = Opportunity.findById(404)
        println opportunity
        println("hehhe")
        avicAheadSubmitService.avicAheadSubmit(opportunity)
    }

    /**
     * 传递5010报文接口*/
    @Secured(['permitAll'])
    @Transactional
    def sendData()
    {
        def xml = """
<REQ>
   <HEAD>
      <BchCde>900000000</BchCde>
      <MsgId>0000093956</MsgId>
      <MsgNo>5010</MsgNo>
      <MsgRef>0000093956</MsgRef>
      <ReqCode>CMIS</ReqCode>
      <Teller>lixiaole</Teller>
      <WorkData>20160812</WorkData>
      <WorkTime>163504</WorkTime>
   </HEAD>
   <MSG>
      <ApplSeq>752716</ApplSeq>
      <CustName>佰仟测试004</CustName>
      <IdTyp>22</IdTyp>
      <IdNo>佰仟测试004</IdNo>
      <AppConclusion>20</AppConclusion>
      <AppAdvice>20</AppAdvice>
      <CrtUsr>lixiaole</CrtUsr>
      <CrtDt>2016-03-27 00:00:00</CrtDt>
   </MSG>
</REQ>
"""
        println xml
        def xml1 = new XmlParser().parseText(xml)
        println xml1.MSG.ApplSeq.text()
        URL url = new URL("http://localhost:8080/Opportunity/serviceMethod5010")
        HttpURLConnection connection = (HttpURLConnection) url.openConnection()
        connection.setDoOutput(true)
        connection.setRequestMethod("POST")
        connection.setRequestProperty("Content-Type", "application/xml")
        connection.outputStream.withWriter { Writer writer -> writer.write xml }
        try
        {
            if (connection.getResponseCode() == 200)
            {
                render 200
            }
        }

        catch (Exception e)
        {
            render 400
        }

    }

    /**
     * 5010贷款申请审批反馈信息*/
    @Secured(['permitAll'])
    @Transactional
    def serviceMethod5010()
    {
        println "Good"
        def respxml = request.XML
        //println respxml.MSG.ApplSeq.text()
        def sw = new java.io.StringWriter()
        def xml = new groovy.xml.MarkupBuilder(sw)
        xml.RESP {
            HEAD {
                // 申请渠道码
                ReqCode('WBJF')
                // 报文编号，交易码
                MsgNo('5010')
                //报文标识号
                MsgId("WBJFZJXF" + new Date().format("yyyyMMdd") + "000001")
                //报文参考号,同MsgId
                MsgRef("WBJFZJXF" + new Date().format("yyyyMMdd") + "000001")
                //工作日期
                WorkData(new Date().format("yyyyMMdd"))
                //工作时间
                WorkTime(new Date().format("HHmmss"))
                def channelRecord = com.next.ChannelRecord.findByApplySeq(respxml.MSG.ApplSeq.text())
                println(respxml.MSG.AppConclusion.text())
                println(channelRecord.applySeq)
                // 根据ApplSeq的值设定状态
                if (channelRecord.applySeq.toDouble() > 0)
                {
                    channelRecord.status = respxml.MSG.AppConclusion.text()
                    if (channelRecord.validate())
                    {
                        channelRecord.save flush: true
                        println "成功插入"
                    } else
                    {
                        println channelRecord.errors
                        println("cuowu")
                    }
                    println(channelRecord)
                    if (respxml.MSG.AppConclusion.text() == '10' || respxml.MSG.AppConclusion.text() == '20' || respxml.MSG.AppConclusion.text() == '30')
                    {
                        ErrorCode('0000')
                        ErrorMsg('交易成功')
                    } else
                    {
                        ErrorCode('9001')
                        ErrorMsg('数据验证错误')
                    }
                }
                // 错误信息
                if (respxml.MSG.ApplSeq.text() == null)
                {
                    ErrorCode('9998')
                    ErrorMsg('无此交易码')
                }
            }
        }

        println sw
    }

    /**
     * //3.29 申请审批结果推送(回调)
     * @return
     */
    @Secured(['permitAll'])
    @Transactional
    def evaluate()
    {
        println("enter in")
        //放回Json报文
        def json = request.JSON
        println(ChannelRecord.findByInterfaceCode("04001001")?.loanApplyNo)
        println(ChannelRecord.find("from ChannelRecord as a where a.interfaceCode='04002017' and a.loanApplyNo='${json["loanApplyNo"]}'"))
        println("hen  hao")
        try
        {
            if (ChannelRecord.find("from ChannelRecord as a where a.interfaceCode='04002017' and a.loanApplyNo='${json["loanApplyNo"]}'") != null)
            {
                println("you shu") //更新
                def channelRecord = ChannelRecord.find("from ChannelRecord as a where a.interfaceCode='04002017' and a.loanApplyNo='${json["loanApplyNo"]}'")
                channelRecord.startTime = new Date()
                channelRecord.interfaceCode = '04002017'
                channelRecord.loanApplyNo = json["loanApplyNo"]
                channelRecord.status = json["appConclusion"]
                channelRecord.crtDt = json["crtDt"]
                channelRecord.opportunity = ChannelRecord.findByInterfaceCode("04001001").opportunity
                channelRecord.createdBy = com.next.User.findByUsername("zz")
                channelRecord.endTime = new Date()
                if (channelRecord.validate())
                {
                    channelRecord.save flush: true
                    println("insert succeed")
                } else
                {
                    println channelRecord.errors
                    println("cuowu")
                }
            } else
            {
                println("kong")
                def channelRecord = new com.next.ChannelRecord()
                channelRecord.startTime = new Date()
                channelRecord.interfaceCode = '04002017'
                channelRecord.loanApplyNo = json["loanApplyNo"]
                channelRecord.status = json["appConclusion"]
                channelRecord.crtDt = json["crtDt"]
                println(json["crtDt"])
                channelRecord.opportunity = ChannelRecord.findByInterfaceCode("04001001").opportunity
                channelRecord.createdBy = com.next.User.findByUsername("zz")
                channelRecord.endTime = new Date()
                if (channelRecord.validate())
                {
                    channelRecord.save flush: true
                    println("insert succeed")
                } else
                {
                    println channelRecord.errors
                    println("cuowu")
                }
            }
        }
        catch (Exception e)
        {
            render ""
        }
        def huidiao = [:]
        huidiao["loanApplyNo"] = json["loanApplyNo"]
        def huidiaowen = new JSON(huidiao)
        render huidiaowen

    }

    /**
     * 结清证明打印*/
    @Secured(['permitAll'])
    @Transactional
    def closingProof(Opportunity opportunity)
    {
        def map = [:]
        def cityName = opportunity?.parent?.user?.city?.name
        if (cityName)
        {
            if (cityName == "北京")
            {
                cityName = "BJ"
            } else if (cityName == "上海")
            {
                cityName = "SH"
            } else if (cityName == "成都")
            {
                cityName = "CD"
            } else if (cityName == "青岛")
            {
                cityName = "QD"
            } else if (cityName == "济南")
            {
                cityName = "JN"
            } else if (cityName == "郑州")
            {
                cityName = "ZJ"
            } else if (cityName == "南京")
            {
                cityName = "NJ"
            } else if (cityName == "西安")
            {
                cityName = "XA"
            } else if (cityName == "合肥")
            {
                cityName = "HF"
            } else if (cityName == "武汉")
            {
                cityName = "WH"
            } else if (cityName == "苏州")
            {
                cityName = "SZ"
            } else if (cityName == "石家庄")
            {
                cityName = "SJZ"
            } else if (cityName == "厦门")
            {
                cityName = "XM"
            }
        }
        map["city"] = cityName
        if (opportunity?.parent?.actualLendingDate)
        {
            map["actualLendingDate"] = opportunity?.parent?.actualLendingDate.format("yyyy年MM月dd日")
        } else
        {
            map["actualLendingDate"] = opportunity?.parent?.actualLendingDate
        }
        def users = OpportunityContact.findAllByOpportunity(opportunity?.parent)
        def fullName = ""
        users.each {
            fullName += it.contact?.fullName + ","
        }
        if (users)
        {
            map["fullName"] = StringUtils.substringBeforeLast(fullName, ",")
        } else
        {
            map["fullName"] = ""
        }
        def bills = Bills.findByOpportunity(opportunity?.parent)
        if (bills?.capital)
        {
            map["principal"] = billsService.transforNumToRMB(bills?.capital)
        } else
        {
            map["principal"] = billsService.transforNumToRMB(opportunity?.parent?.actualLoanAmount == 0 ? opportunity?.parent?.actualAmountOfCredit : opportunity?.parent?.actualLoanAmount)
        }

        def contract = Contract.executeQuery("select c.serialNumber from OpportunityContract oc left join oc.contract c left join c.type t left join oc.opportunity o where o.id = ${opportunity?.parent?.id} and t.name = '借款合同'")
        if (contract)
        {
            map["serialNumber"] = contract[0]
        } else
        {
            map["serialNumber"] = ""
        }
        respond opportunity, model: [map: map], view: "closingProof"
    }
}
